<template>
  <div class="w-[100%] h-[100%]">

    <div
      class="w-[100%] h-[48px] bg-[rgba(255,78,0,0.04)] pl-[20px] flex items-center text-[#FF4E00]">
      <Icon icon="ep:bell-filled" color="#FF4E00"/>
      <span
        class="ml-[10px]">采购建议生成规则：采购建议=总需求-总库存=订单占用数-（在途库存+未审核在途库存+实际库存）</span>
    </div>

    <div class="mt-[30px]">
      <ContentWrap>
        <SearchBox :queryForm="searchList" :showExpland="false" @query="handleSearchQuery"
                   :show-export="false" :show-len="4"/>
      </ContentWrap>
    </div>

    <div class="line mt-[30px] w-[100%] h-[1px] " style="border: dashed 1px #DDDDDD"></div>

    <div class="mt-[30px]">
      <el-button @click="handleBtnClick({type:'add'})" type="primary" color="#3721FF"
                 class="mr-[13px]">
        批量采购
      </el-button>

      <el-dropdown placement="bottom-start">
        <el-button>导出
          <Icon icon="ep:arrow-down" class="ml-5px"/>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleBtnClick({type:'export',data:'all'})">导出所有
            </el-dropdown-item>
            <el-dropdown-item @click="handleBtnClick({type:'export',data:'selected'})">导出选中
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </div>

    <div class="mt-[30px]">
      <QueryTable
        :list="dataList"
        :total="total"
        :btns="tableBtnList"
        @execute="handleBtnClick"
        v-model="queryParams"
        :thead="th"
        :show-action="true"
      >
        <template #cover="{row}">
          <ImagePreview :src="row.cover" width="38px" height="38px"/>
        </template>

        <template #sku="{row}">
          <div>
            <div>{{ row.property }}/</div>
            <div>{{ row.sku }}</div>
          </div>
        </template>

        <template #productName="{row}">
          <div>
                 <div class="text-[#3721FF] cursor-pointer" v-copyText="row.productName">{{
                     row.productName
                   }}</div>

            <div class="text-[#3721FF] cursor-pointer" v-copyText="row.code">{{
                row.code
              }}</div>

          </div>

        </template>
        <template #productId="{row}">
          <span class="text-[#3721FF] cursor-pointer" v-copyText="row.productId">{{
              row.productId
            }}</span>
        </template>

      </QueryTable>

    </div>
    <PurchaseLink v-model="isShowDialog" :info="selectedRow" @confirm="handleBtnClick"/>
    <InfoAction v-model="isShowAction" :info="selectedRows" @confirm="handleBtnClick"/>
  </div>
</template>
<script setup lang="ts">
import dayjs from "dayjs";
import Icon from "@/components/Icon/src/Icon.vue"
import QueryTable from "@/components/TableData/index.vue"
import ImagePreview from "@/components/ImagePreview/index.vue"
import PurchaseLink from "@/views/purchase/advice/components/PurchaseLink.vue";
import InfoAction from "./components/InfoAction.vue";
import type {TradeOrderQueryVO} from "@/api/mall/trade/order";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {useUserStore} from "@/store/modules/user";

import {PurchaseAdviceVO, ProductPurchaseRespVO} from "@/api/erp/purchase/advice";

import {PurchaseAdviceApi} from "@/api/erp/purchase/advice";
import {throttle} from "@/utils";
import {PurchaseOrderApi} from "@/api/purchase/order";
import {PurchaseSuggestApi} from "@/api/purchase/advice";

const message = useMessage();
const user = useUserStore();


const searchList: TradeOrderQueryVO[] = [


  {
    label: '商品名称/ID',
    code: 'productName',
    type: 'input',
  },
  {
    label: 'sku',
    code: 'sku',
    type: 'input'
  },
  {
    label: '属性',
    code: 'property',
    type: 'input',
  },
  {
    label: '内部编码',
    code: 'code',
    type: 'input'
  },
]
const initQueryParams = {
  pageNo: 1, pageSize: 10
}

const tableBtnList = ref([
  {
    color: '#3721FF',
    code: 'link',
    name: '采购链接'
  }
]);


const th = ref([
  {
    name: '封面',
    code: 'cover',
    type: 'numberRanger',
    search: true
  },
  {
    name: '规格值/sku',
    code: 'sku',
    type: 'date',
    search: true
  },
  {
    name: '商品名称',
    code: 'productName',
    search: false
  },
  {
    name: '商品ID',
    code: 'productId',
    type: 'numberRanger',
    search: true
  },
  {
    name: '采购建议',
    code: 'productSuggestions',
    search: false
  },
  {
    name: '订单占用数',
    code: 'orderOccupancyCount',
    search: false
  },
  {
    name: '实际库存',
    code: 'onHandInventory',
    search: false
  },
  {
    name: '在途库存',
    code: 'inTransitStock',
    search: false
  },
  {
    name: '未审核在途库存',
    code: 'unreviewedInTransitInventory',
    search: false
  },
  {
    name: '更新时间',
    code: 'updateTime',
    date: true
  }
]);

const dataList = ref<PurchaseAdviceVO[]>([]);

const ids = ref<Array<string | number>>([]);
const total = ref(0);

const initRow: PurchaseAdviceVO = {
  cover: undefined,
  id: 0,
  inTransitStock: undefined,
  mainType: undefined,
  onHandInventory: undefined,
  orderOccupancyCount: undefined,
  productCode: undefined,
  productId: undefined,
  productName: undefined,
  productPurchaseRespVOList: [],
  productSuggestions: undefined,
  property: undefined,
  sku: undefined,
  unreviewedInTransitInventory: undefined,
}

const selectedRow = ref<PurchaseAdviceVO>({...initRow})

const selectedRows = ref<PurchaseAdviceVO[]>([])

const isShowDialog = ref(false);

const isShowAction = ref(false)


const queryParams = ref({
  ...initQueryParams
})

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */

  queryParams.value = {
    ...initQueryParams,
    ...val
  }
  queryList();
}

const handleBtnClick = e => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const fn = {
  pagination(){
    queryList()
  },
  purchaseLinkConfirm: throttle(async (e) => {
    let list = e.data.dataList;

    let arr = [];
    list.forEach(item => {
      arr = arr.concat(item.productPurchaseDOList);
    })

    let res = await PurchaseSuggestApi.addProductLink(arr);

    message.success("操作成功")

  }, 1000),
  selectionChange({data}) {
    ids.value = data.ids;
  },
  add() {
    if (ids.value && ids.value.length > 0) {
      let list = dataList.value.filter(item => {
        let isIn = ids.value.find(at => {
          return at == item.id
        })

        return !!isIn
      })
      selectedRows.value = list.map(item => {
        return {...item, purchaseNumber: 1, purchaseAmount: '0.00'}
      });
      isShowAction.value = true;
    } else {
      message.error('请选择要采购的商品')
    }
    console.log("点击批量采购")
  },
  export: throttle(({data}) => {
    console.log(data)
  }, 1000),
  link({data}) {
    selectedRow.value = data.row;
    isShowDialog.value = true
  },
  purchaseConfirm: throttle(async ({data}) => {
    console.log(user)
    let res = await PurchaseOrderApi.createPurchaseOrder({
      ...data.form,
      purchaseName: user.user.nickname,
      purchaseDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      purchaseOrderDetailRespVOList: data.dataList.map(item => {
        return {
          ...item,
          purchaseSuggestId: item.id
        }
      })
    })
    //
    queryList();
    message.success("采购订单创建成功")
  }, 1000)
}

const queryList = async () => {
  let res = await PurchaseAdviceApi.getPurchaseAdvicePage(queryParams.value);
  console.log("666", res)
  total.value = res.total;
  dataList.value = res.list || [];
}

onMounted(() => {
  queryList();
})


</script>
<style lang="scss" scoped>

</style>
